package com.changgou.order.service.impl;

import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.feign.SpuFeign;
import com.changgou.goods.pojo.pojo.Sku;
import com.changgou.goods.pojo.pojo.Spu;
import com.changgou.order.pojo.OrderItem;
import com.changgou.order.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {
  @Autowired private SkuFeign skuFeign;
  @Autowired private SpuFeign spuFeign;
  @Autowired
  private RedisTemplate redisTemplate;

  @Override
  public void add(Long id, Integer num,String username) {
      //如果商品的数量为0
      if(num <0){
          //移除该商品的购物车
          redisTemplate.boundHashOps("Cart_"+username).delete(id);
          //如果此时的购物车为空，移除当前的购物车
          Long size = redisTemplate.boundHashOps("Cart_" + username).size();
          if (size==null &&size<=0){
              redisTemplate.delete("Cart_"+username);
          }
          return;
      }
    // 查询商品详情
    Sku sku = skuFeign.findById(id).getData();
    Spu spu = spuFeign.findById(sku.getSpuId()).getData();
    // 将购物车的对象封装成OrderItem
      OrderItem orderItem = CreateOrderItem(num, sku, spu);
      // 将购物的信息存入到redis中
      redisTemplate.boundHashOps("Cart_"+username).put(id, orderItem);

  }

    /**
     * 购物车查询的列表实现
     * @param username
     * @return
     */
    @Override
    public List<OrderItem> list(String username) {
        List<OrderItem> orderItemList = redisTemplate.boundHashOps("Cart_" + username).values();
        return orderItemList;
    }

    /**
     * 封装对象
     * @param num
     * @param sku
     * @param spu
     * @return
     */
    private OrderItem CreateOrderItem(Integer num, Sku sku, Spu spu) {
        OrderItem orderItem = new OrderItem();
        orderItem.setCategoryId1(spu.getCategory1Id());
        orderItem.setCategoryId2(spu.getCategory2Id());
        orderItem.setCategoryId3(spu.getCategory3Id());
        orderItem.setSpuId(spu.getId());
        orderItem.setSkuId(sku.getId());
        orderItem.setName(sku.getName());
        orderItem.setPrice(sku.getPrice());
        orderItem.setNum(num);
        orderItem.setMoney(num* orderItem.getPrice());
        orderItem.setImage(spu.getImage());
        return orderItem;
    }
}
